﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Mvc;
using GameSchoolApplication.Repository;
using GameSchoolApplication.Models;

namespace GameSchoolApplication.Controllers
{
    public class AssignmentController : Controller
    {
        private GameSchoolWebContext _db = new GameSchoolWebContext();
        private GameRepository _game = new GameRepository();
        private TaskRepository _task = new TaskRepository();

        
		/// <summary>
		/// Gets the assignment you are assking for
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
        public ActionResult Details(int id)
        {
            Assignment assignment = _task.GetAssignmentById(id);
            return View(assignment);
        }
        
		/// <summary>
		/// Sends in a specific levelId to connect it to
		/// the assignment you are creating
		///  </summary>
		/// <param name="levelId"></param>
		/// <returns></returns>
        [HttpGet]
        public ActionResult Create(int levelId)
        {
            Level level = _game.GetLevelById(levelId);
            return View(new Assignment { Level = level, LevelId = levelId });
        }

		/// <summary>
		/// Posts a Assignemt that has been created
		/// and links it to a specific level 
		/// </summary>
		/// <param name="assignment"></param>
		/// <returns></returns>
        [HttpPost]
        public ActionResult Create(Assignment assignment)
        {
            if (ModelState.IsValid)
            {
                _task.AddAssignment(assignment);
                return RedirectToAction("Details", "Level", new { id = assignment.LevelId });
            }
			return View(assignment);         
        }
	        
		/// <summary>
		/// Displays the points/grade from this specific 
		/// asssignment
		/// </summary>
		/// <param name="handInId"></param>
		/// <returns></returns>
        [HttpGet]
        public ActionResult Grade(int handInId)
        {
            StudentAssignmentPoints grade = _task.GetStudentAssignmentPoints(handInId);
            return View(grade);
        }

		/// <summary>
		/// Posts the grade from the current assignment
		/// and add's it to the database
		/// </summary>
		/// <param name="grade"></param>
		/// <returns></returns>
        [HttpPost]
        public ActionResult Grade(StudentAssignmentPoints grade)
        {
            if (ModelState.IsValid)
            {
                _task.UpdateStudentAssignmentPoints(grade);
                return RedirectToAction("Grade", new { handInId = grade.Id });
            }
            return View(grade);
        }

		/// <summary>
		/// Downloads the assignment that the student hands in
		/// into the database
		/// </summary>
		/// <param name="handInId"></param>
		/// <returns></returns>
        [HttpGet]
        public ActionResult Download(int handInId)
        {
            StudentAssignmentPoints handIn = _task.GetStudentAssignmentPoints(handInId);
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads/assignments"), handIn.AssignmentId.ToString(), handIn.StudentId.ToString(), handIn.FileName);
            if (System.IO.File.Exists(path))
            {
                return File(path, "application/octet-stream");
            }
            return RedirectToAction("Grade", new { id = handIn.AssignmentId, studentId = handIn.StudentId });
        }

		/// <summary>
		/// The assignment that the student hands in
		/// specified by the assignmentId
		/// </summary>
		/// <param name="assignmentId"></param>
		/// <returns></returns>
        [HttpGet]
        public ActionResult HandIn(int assignmentId)
        {
            Assignment assignment = _task.GetAssignmentById(assignmentId);
            Person student = _db.Persons.Where(p => p.UserName == User.Identity.Name).SingleOrDefault();
            StudentAssignmentPoints handIn = _task.GetStudentAssignmentPoints(assignment, student);
            if (handIn == null)
            {
                handIn = new StudentAssignmentPoints { Assignment = assignment, AssignmentId = assignmentId, Student = student, StudentId = student.Id };
            }
            ViewBag.TimeLeft = handIn.LevelEntry.StartedAt.AddDays(handIn.Assignment.Days).Subtract(DateTime.Now);
            return View(handIn);
        }

		/// <summary>
		/// Student posts the assignment that he wants to hand in 
		/// </summary>
		/// <param name="handIn"></param>
		/// <param name="fileBase"></param>
		/// <returns></returns>
        [HttpPost]
        public ActionResult HandIn(StudentAssignmentPoints handIn, HttpPostedFileBase fileBase)
        {
            if (ModelState.IsValid)
            {
                handIn.StudentId = _db.Persons.Where(p => p.UserName == User.Identity.Name).SingleOrDefault().Id;
                if (fileBase.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(fileBase.FileName);
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads/assignments"), handIn.AssignmentId.ToString(), handIn.StudentId.ToString());
                    Directory.CreateDirectory(path);
                    fileBase.SaveAs(Path.Combine(path, fileName));
                    handIn.FileName = fileName;
                }
                else
                {
                    return View(handIn);
                }
                _task.AddStudentAssignmentPoints(handIn);
                return RedirectToAction("StudentGames", "Game");
            }
            else
            {
                return View(handIn);
            }
        }

    }
}
